package com.botarena.server.dao;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.botarena.server.dao.filter.Filter;
import com.botarena.server.model.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public abstract class GenericDAO<E extends Entity> implements DAO<E> {
	
	private final Class<E> persistentClass;
	protected final PersistenceManager pm;

	@SuppressWarnings("unchecked")
	public GenericDAO(PersistenceManager pm) {
		persistentClass = (Class<E>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		this.pm = pm;
	}

	public Class<E> getPersistentClass() {
		return persistentClass;
	}

	@Override
	public void create(E entity) {
		pm.makePersistent(entity);
	}
	
	@Override
	public void create(Collection<E> entities) {
		pm.makePersistentAll(entities);
	}

	@Override
	public void delete(E entity) {
		pm.deletePersistent(entity);
	}
	
	@Override
	public void deleteAll(Collection<E> entities) {
		pm.deletePersistentAll(entities);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public int deleteAll(int limit) {
		Query query = pm.newQuery(getPersistentClass());
		query.setRange(0, limit);
		List<E> entities = (List<E>) query.execute();
		int deleted = entities.size();
		deleteAll(entities);
		return deleted;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<E> getAll() {
		Query query = pm.newQuery(getPersistentClass());
		return (List<E>) query.execute();
	}

	@Override
	public List<E> getAll(Filter<E> filter) {
		List<E> all = getAll();
		List<E> filtered = new ArrayList<E>();
		for (E e : all) {
			if (filter.accept(e)) {
				filtered.add(e);
			}
		}
		return filtered;
	}

	@Override
	public E getByKey(Key key) {
		return pm.getObjectById(getPersistentClass(), key);
	}
	
	@Override
	public E getByKey(String key) {
		return pm.getObjectById(getPersistentClass(), KeyFactory.stringToKey(key));
	}

	@Override
	@SuppressWarnings("unchecked")
	public Collection<E> getByKeys(Collection<Key> keys) {
		Query query = pm.newQuery(getPersistentClass());
		query.setFilter("keys.contains(key)");
		query.declareParameters("Collection keys");
		query.declareImports("import " + Collection.class.getName());
		return (Collection<E>) query.execute(keys);
	}
}
